const {
    ServiceType,
    appendServices
} = require("./base");
const fs = require('fs');
const util = require("../util");
const config = util.config;
const routers = {
    "/config/get": ServiceType(),
    "/config/up": ServiceType(),
    "/proxy": ServiceType(),
}
const G = {
    configPath: config.rootPath + "/src/config.js",
    excludeKey: [
        "path"
    ]
}

init();
module.exports = routers;
function init(){
    let services = {};
    createServices(services);

    appendServices(routers, services);
}
function createServices(services){
    services["/config/get"] = function(req, res, body) {
        return config;
    }

    services["/config/up"] = async function(req, res, body) {
        for (const key in util) {
            if (body[key] !== undefined && G.excludeKey.find(key) == undefined) {
                config[key] = body[key]
            }
        }
        if(body.save) {
            await fs.promises.writeFile(task.path, JSON.stringify(config, null, 2));
        }
        return config;
    }

    services["/proxy"] = async function(req, res, body) {
        let proxyUrl = body.proxyUrl;
        delete body.proxyUrl;
        // 使用axios发起新的请求
        const response = await axios({
            method: req.method,
            url: proxyUrl,
            params: body, // GET参数
            data: body,   // POST数据，axios会根据请求方法自动选择使用哪个
            headers: req.headers,
        });

        // 将响应转发给原始请求的客户端
        res.status(response.status).json(response.data);
    }
    
}